package com.peycard.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.peycard.common.PortalUserDTO;

/**
 * Servlet Filter implementation class PortalFilter
 */
public class PortalFilter implements Filter {

	private static Logger LOGGER = LoggerFactory.getLogger(PortalFilter.class);

	/**
	 * Default constructor.
	 */
	public PortalFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpSession session = request.getSession();
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		LOGGER.info("AUTH:[" + auth.toString() + "]");
		String username = auth.getName();
		LOGGER.info("USER:[" + username.toString() + "]");

		PortalUserDTO portalUser = (PortalUserDTO) session
				.getAttribute("userAuthentication");
		if (portalUser != null) {
			int firstAccess = portalUser.getFirstAccess();

			switch (firstAccess) {
			case 0:
				session.setAttribute("SPRING_SECURITY_CURRENT_USER", username);
				RequestDispatcher requestDispatchet = request
						.getRequestDispatcher("/home.jsp");
				requestDispatchet.forward(servletRequest, servletResponse);
				break;

			case 1:
				RequestDispatcher requestDisp = request
						.getRequestDispatcher("/reestablece.jsp");
				requestDisp.forward(servletRequest, servletResponse);
				break;

			default:
				break;
			}
		}
		chain.doFilter(servletRequest, servletResponse);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
